// 模拟数据
let staffData;

// 修改后的JavaScript部分
let currentEditIndex = -1;
let originalPermission = '';


// 初始化表格
async function renderTable() {
    const response = await GetEmployeeList();

    if (!response.data) {
        return;
    }


    staffData = response.data;

    const tbody = document.getElementById('staffList')

    tbody.innerHTML = response.data.map((staff, index) => `
        <tr onclick="showDetail(${index})">
            <td>${staff.Name}</td>
            <td>${staff.Account}</td>
            <td>${staff.Company}</td>
            <td>${staff.Department}</td>
            <td>${staff.IsAdmin ? "管理员" : "普通用户"}</td>
            <td>
            ${(() => {
            try {
                const permissions = JSON.parse(staff.Permission);
                let permisionAll = '';

                if (permissions.machineEdit == '1') {
                    if (permisionAll.length > 0) {
                        permisionAll += ','
                    }
                    permisionAll += '编辑'
                }

                if (permissions.machineRead == '1') {
                    if (permisionAll.length > 0) {
                        permisionAll += ','
                    }
                    permisionAll += '读取'
                }

                return `<span class="permission-tag">${permisionAll}</span>`

            } catch (e) {
                return '<span class="error">权限解析错误</span>';
            }
        })()}
        </td>
        </tr>
    `).join('')
}


function showDetail(index) {
    const staff = staffData[index];
    currentEditIndex = index;
    originalPermission = staff.Permission; // 保存原始权限

    const jsPermission = JSON.parse(staff.Permission);


    const modalContent = `
        <div class="detail-item">
            <strong>姓名：</strong>${staff.Name}
        </div>
        <div class="detail-item">
            <strong>账号：</strong>${staff.Account}
        </div>
        <div class="detail-item">
            <strong>公司：</strong>${staff.Company}
        </div>
        <div class="detail-item">
            <strong>部门：</strong>${staff.Department}
        </div>
        <div class="detail-item">
            <strong>角色：</strong>
            <select class="permission-select" id="roleSelect">
                <option ${staff.IsAdmin === 1 ? 'selected' : ''}>管理员</option>
                <option ${staff.IsAdmin === 0 ? 'selected' : ''}>普通用户</option>                
            </select>
        </div>
        <div class="detail-item">
            <strong>权限：</strong>
            <div class="checkbox-group">
                <label class="checkbox-label">
                    <input type="checkbox" 
                        id="readPermission" 
                        name="machineRead" 
                        ${jsPermission.machineRead === '1' ? 'checked' : ''}>
                    <span>读取</span>
                </label>
                <label class="checkbox-label">
                    <input type="checkbox" 
                        id="editPermission" 
                        name="machineEdit" 
                        ${jsPermission.machineEdit === '1' ? 'checked' : ''}>
                    <span>编辑</span>
                </label>
            </div>
        </div>
        <div class="modal-actions">
            <button class="confirm-btn" onclick="handleConfirm()">确定</button>
            <button class="cancel-btn" onclick="handleCancel()">取消</button>                    
        </div>
    `;

    document.getElementById('modalContent').innerHTML = modalContent;
    document.getElementById('detailModal').style.display = 'block';
}

// 新增处理函数
async function handleConfirm(index) {
    try {
        let permissionInfo = staffData[currentEditIndex];

        // 获取角色选择
        const roleSelect = document.getElementById('roleSelect');
        const isAdmin = roleSelect.options[roleSelect.selectedIndex].text === '管理员';

        // 获取权限状态
        const permissions = {
            machineRead: document.getElementById('readPermission').checked ? '1' : '0',
            machineEdit: document.getElementById('editPermission').checked ? '1' : '0'
        };

        permissionInfo.IsAdmin = isAdmin ? 1:0;

        const jsPermission = JSON.parse(permissionInfo.Permission);
        jsPermission.machineRead = permissions.machineRead;
        jsPermission.machineEdit = permissions.machineEdit;

        permissionInfo.Permission = JSON.stringify(jsPermission);

        const token = localStorage.getItem('authToken');
        // 发起请求
        const response = await fetch('/api/employee/update', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `${token}`,
            },
            body: JSON.stringify(permissionInfo),
        });

        if (!response.ok) {
            if (response.status == 401) {
                AuthReDirection(false);
            }
            else if (response.status == 402) {
                const data = await response.json();
                AuthPermissionErr(data.error);
                return
            }
            else {
                //alert(`删除失败,接口调用失败`)
                throw new Error('删除失败,接口调用失败');
            }
        } else {
            // 解析业务数据
            const result = await response.json();
            // 根据code字段判断业务状态
            if (result.code === "0") {
                ShowNotice({
                    message: '修改成功',
                    type: 'success',
                    duration: 2000
                });

                closeModal();

                renderTable();
            } else {
                const errMessage = result.message;                
                throw new Error(errMessage);
            }

        }

    } catch (err) {
        const results = await ShowErrorModal(err, {
            title: '更新失败',
            buttons: [
                {
                    text: '确定',
                    type: 'confirm',
                    onClick: () => console.log('确认')
                }
            ]
        });
    }    
}

function handleCancel() {
    // 恢复原始权限
    staffData[currentEditIndex].permission = originalPermission;
    closeModal();
}

// 修改关闭函数
function closeModal() {
    document.getElementById('detailModal').style.display = 'none';
    renderTable();
    currentEditIndex = -1; // 重置索引
}

// 更新权限
function updatePermission(index, value) {
    staffData[index].permission = value
}

// 返回处理
function handleBack() {
    // 此处可替换为实际返回逻辑
    //window.history.back()
    window.location.href = 'home';
}

// 初始化
renderTable()

// 点击遮罩层关闭
document.getElementById('detailModal').addEventListener('click', (e) => {
    if (e.target.classList.contains('modal-mask')) {
        closeModal()
    }
})



async function GetEmployeeList() {
    try {
        // 获取认证信息（根据实际存储方式调整）
        const token = localStorage.getItem('authToken');
        if (!token) AuthReDirection(false);

        const response = await fetch(`/api/employee/list`, {
            method: 'GET',
            headers: new Headers({
                'Authorization': `${token}`
            }),
        });
        if (!response.ok) {
            if (response.status == 401) {
                AuthReDirection(false);
            }
            else if (response.status == 402) {
                const data = await response.json();
                AuthPermissionErr(data.error);
                return
            }
            else {
                throw new Error('数据加载失败')
            }
        }

        return response.json();
    } finally {

    }
}
